#!/bin/sh

set -e

REPO_ROOT_DIR="$(git rev-parse --show-toplevel)"

files=$((git diff --cached --name-only --diff-filter=ACMR | grep -Ei "\.java$") || true)
if [ ! -z "${files}" ]; then
  comma_files=$(echo "$files" | paste -s -d "," -)

  # Checkstyle does not have the functionality of auto-fixing.
  # So run `goJF` before `checkJava`.
  "${REPO_ROOT_DIR}/gradlew" goJF -DgoogleJavaFormat.include="$comma_files"
  "${REPO_ROOT_DIR}/gradlew" checkJava -DcheckJavaInclude="$comma_files"

  git add $(echo "$files" | paste -s -d " " -)
fi
